<template>
  <div class="app-container">
    <!-- 搜索区 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">

      <el-form-item label="字典类型" prop="dictType">
        <el-select v-model="queryParams.dictType" placeholder="请选择" clearable @change="handlerDictTypeChange">
            <el-option
              v-for="item in dictTypeList"
              :key="item.id"
              :label="item.dictName"
              :value="item.dictType">
            </el-option>
          </el-select>
      </el-form-item>

      <el-form-item label="字典标签" prop="dictLabel">
        <el-input v-model="queryParams.dictLabel" placeholder="请输入字典标签" clearable style="width: 240px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择" clearable>
            <el-option
              v-for="item in dicts.sys_normal_disable"
              :key="item.id"
              :label="item.dictLabel"
              :value="item.dictValue">
            </el-option>
          </el-select>
     </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
      </el-form-item>
    </el-form>

     <!-- 功能区 -->
     <el-row>
       <el-col :span="24">
          <el-button type="primary" size="small"  @click="handlerAdd()" >新增</el-button>
          <el-button type="warning" size="small"  @click="handlerUpdate()" :disabled="single" >修改</el-button>
          <el-button type="success" size="small"  @click="handlerExcel()"  >导出</el-button>
          <el-button type="warning" size="small"  @click="handlerClose()"  >关闭</el-button>
       </el-col>
     </el-row>

    <el-table :data="tableData.rows" border style="width: 100%"  v-loading="loading" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"  />
      <el-table-column prop="id" label="编号" width="80" />
      <el-table-column prop="dictLabel" label="字典标签"  />
      <el-table-column prop="dictValue" label="字典键值" />
      <el-table-column prop="dictSort" label="字典排序" />

      <el-table-column label="状态" width="180">
        <template slot-scope="scope">
          <el-tag  v-for="item in dicts.sys_normal_disable" :key="item.id" v-if="item.dictValue=== scope.row.status" :type="item.listClass" >{{item.dictLabel}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="remark" label="备注"  />

      <el-table-column prop="createTime" label="创建时间" width="180" />

      <el-table-column label="操作" align="left" width="160" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button   size="mini" type="text" icon="el-icon-edit" @click="handlerUpdate(scope.row)">修改</el-button>
          <el-button v-if="scope.row.status==='0'" size="mini"  type="text" icon="el-icon-delete" style="color:red;" @click="handlerDisable(scope.row)">停用</el-button>
          <el-button v-else-if="scope.row.status==='1'" size="mini" type="text" icon="el-icon-video-play" @click="handlerEnable(scope.row)">启用</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页条 -->
    <el-pagination v-if="tableData.total>0" :current-page="queryParams.page" :page-sizes="[1, 5, 10, 20,30,50,100]"
      :page-size="queryParams.size" layout="total, sizes, prev, pager, next, jumper" :total="tableData.total"
      @size-change="handleSizeChange" @current-change="handleCurrentChange" />


    <!-- 新增和修改的对话框 -->
    <el-dialog 	v-bind:title="title"  :visible.sync="dialogVisible"  width="500px"  :close-on-click-modal="false"   >
      <!-- 内容 -->
    				<el-form ref="form" :model="form" label-width="80px">
             <el-form-item   label="字典类型"  >
               <b>{{queryParams.dictType}}</b>
             </el-form-item>

              <el-form-item   label="数据标签" prop="dictLabel" :rules="[{ required: true, message: '不能为空', trigger: 'blur' } ]">
                <el-input v-model="form.dictLabel"></el-input>
              </el-form-item>

              <el-form-item   label="数据键值" prop="dictValue" :rules="[{ required: true, message: '不能为空', trigger: 'blur' } ]">
                <el-input v-model="form.dictValue"></el-input>
              </el-form-item>

              <el-form-item   label="样式属性" prop="cssClass"  >
                <el-input v-model="form.cssClass"></el-input>
              </el-form-item>

              <el-form-item   label="显示排序" prop="dictSort"  >
                <el-input-number v-model="form.dictSort" controls-position="right"   :min="0" :max="999"></el-input-number>
              </el-form-item>


              <el-form-item label="状态"  >
                <el-radio-group v-model="form.status">
                    <el-radio v-for="item in dicts.sys_normal_disable" :key="item.id" :label="item.dictValue">{{item.dictLabel}}</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="回显样式" prop="listClass">
                 <el-select v-model="form.listClass" placeholder="请选择">
                     <el-option
                       v-for="item in listClassList"
                       :key="item.value"
                       :label="`${item.label}(${item.value})`"
                       :value="item.value">
                     </el-option>
                   </el-select>
              </el-form-item>

              <el-form-item label="备注"  >
                <el-input  type="textarea" :rows="2"  placeholder="请输入内容"  v-model="form.remark">
                </el-input>
              </el-form-item>
    				</el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="resetForm">取 消</el-button>
          <el-button type="primary" @click="saveFormBefore">确 定</el-button>
        </span>
    </el-dialog>

  </div>
</template>

<script>
  import {dataDictTypes, dataApi, addApi,updateApi ,changeStatusApi ,findByIdApi } from '@/api/dictdata.js'
  import {findByIdApi as dictTypeFindById, dataApi as dictTypePageApi  } from '@/api/dicttype.js'
  export default {
    created() {
      //获取路由参数
      const id=this.$route.params.id
      //有参数
      if(id){
        //加载通用字典值
        this.fetchDictTypes()
        //读取所有的字典类型
        this.fetchDictTypeList()

        //根据id查询dictType的内容
        dictTypeFindById(id).then(resp=> {
          this.queryParams.dictType = resp.data.dictType
          //再查询数据
          this.fetchData()
        })
      }else{
         this.$message.error('参数错误');
         //更改路由地址
         this.$router.push({ path: '/dict' })
      }
    },
    data() {
      return {
        loading: false,
        // 表单查询条件对象
        queryParams:{
          page: 1,
          size: 10,
          dictType: undefined
        },
        // 分页表格分页的结果对象
         tableData: {
           total: 0,
           rows: []
         },
         //表格选中的对象
         mutilrows:[],
         //表格选中对象的主键的值
         ids: [],
         //编辑按钮禁用
         single: true,
         //数据字典返回结果
         dicts: {},
         //所有的数据字典类型列表
         dictTypeList:[],
         //回显示样式值
         listClassList:[
           {
             value: "default",
             label: "默认"
           },
           {
             value: "primary",
             label: "主要"
           },
           {
             value: "success",
             label: "成功"
           },
           {
             value: "info",
             label: "信息"
           },
           {
             value: "warning",
             label: "警告"
           },
           {
             value: "danger",
             label: "危险"
           }
         ],
         //对话框的变量
         title: '添加数据',
         dialogVisible: false,
         form: {
           status: '0',
           listClass: 'default',
           dictSort: 0
         },

      }
    },
    methods: {
      //下拉列表变化的事件
      handlerDictTypeChange(val){
        //重置查询操作
        this.queryParams.page =1
        this.queryParams.dictLabel=undefined
        this.queryParams.status = undefined
        this.fetchData()
      },
      //查询所有的字典分类
      fetchDictTypeList(){
        dictTypePageApi({'page':1,'size':500}).then(resp=> {
          this.dictTypeList = resp.data.list
        })
      },
      //选中表格值的变化事件
       handleSelectionChange(val) {
         console.log(val)
           this.mutilrows = val;
           // this.ids= val.map(function(s){
           //   return  s.id
           // } );
           this.ids=val.map(s=> s.id);
           this.single = val.length!==1
       },
      // 每页几笔发生变化
       handleSizeChange(val) {
          this.queryParams.page=1
          this.queryParams.size=val
          // 重新查询
          this.fetchData()
      },
      // 当前页发生变化
      handleCurrentChange(val) {
          this.queryParams.page=val
           // 重新查询
           this.fetchData()
      },
      // 获取后台的查询数据
      fetchData(){
        this.loading=true
        dataApi(this.queryParams).then(resp=> {
            this.tableData.total = resp.data.total
            this.tableData.rows = resp.data.list
            this.loading =false
        })
      },
      //点击搜索按钮
      handleQuery(){
        this.queryParams.page =1
        this.fetchData()
      },
      //查询数据字典的值
      fetchDictTypes() {
        const params= ['sys_normal_disable']
        dataDictTypes(params).then(resp=> {
           this.dicts = resp.data
        })
      },
      handlerAdd(){
        //得到集合中最大的值 +1
        this.form.dictSort = this.calcArrayMaxValue(this.tableData.rows,'dictSort')
        this.form.dictType = this.queryParams.dictType
        //显示对话框
         this.dialogVisible =true
         this.title='添加数据'
      },
      handlerUpdate(row){
        let id;
         if(row){
           id=row.id
         }else{
           id=this.ids[0]
         }
         //根据主键查询数据，回填充form表单中
         findByIdApi(id).then(resp=> {
           this.form = resp.data

           this.dialogVisible =true
           this.title='编辑数据'
         })
      },
      handlerExcel(){
        if(this.ids && this.ids.length>0){
          this.download('/api/dictdata/download/choice', {'ids':this.ids},`字典明细列表_${new Date().getTime()}.xlsx`)
        }else{
          this.download('/api/dictdata/download', this.queryParams,`字典明细列表_${new Date().getTime()}.xlsx`)
        }
      },
      //重置表单
      resetForm(){
         //清空验证规则样式
         this.$refs['form'].resetFields();
         //清除数据
         this.form={
           status: '0',
           listClass: 'default',
           dictSort: 0
         }
         //关闭对话框
         this.dialogVisible =false
      },
      //提交保存数据之前验证
      saveFormBefore(){
         //验证数据是否都有效了
          this.$refs['form'].validate((valid) => {
           if (valid) {
              //验证成功
              this.$confirm('确定要保存数据吗?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                      }).then(() => {
                         //提交
                          this.saveForm();

                      }).catch(() => {
                        //不提交操作
                      });

           } else {
             return false;
           }
         });
      },
      //向后台提交数据
       saveForm(){
         //修改
         let saveApi;
         if(this.form.id){
            saveApi= updateApi;
         }else{
            saveApi =addApi
         }

         saveApi(this.form).then(resp=> {
             this.$message({message: '操作成功', type: 'success'});
             //关闭窗体
             this.resetForm()
             //重新查询数据
             this.fetchData()
         })

       },
       //停用账户
       handlerDisable(row){
         this.confirmTips('确定要停用该数据吗？',()=>{
           this.changeStates(row.id,'1')
         })
       },
       //启用账户
       handlerEnable(row){
         this.confirmTips('确定要启用该数据吗？',()=> {
           this.changeStates(row.id,'0')
         })
       },
       //更改账号状态
       changeStates(id,status){
          changeStatusApi( {'id': id, 'status': status}).then(resp=> {
            this.$message({message: '操作成功', type: 'success'});
            //重新查询数据
            this.fetchData()
          })
       },
       //跳转路由
       handlerClose(){
         this.$router.push({'path':'/dict'})
       }
    }
  }
</script>

<style>
</style>
